import { base64ToPath } from '@huntianning/miniprogram/utils/file.js'


/**
 * 将图片压缩到指定大小
 * @param { Object } file - 文件信息
 * @param { Number } size - 压缩目标大小，字节单位
 * @example
 * 	compressionImage({
 *		path: 'xxx/xxx.jpg',
 *		size: 2000
 *	})
 */
export function compressionImage (file, toSize = 1 * 1024 * 1024) {
	return new Promise((resolve, reject) => {
		if (!file || !file.path || !file.size) {
			reject('无效文件')
		} else {
			const { size, path } = file
			if (size < toSize) {
				resolve(file)
			} else {
				uni.compressImage({
					src: path,
					quality: 70,
					width: '70%',
					success: res => {
						uni.getFileInfo({
							filePath: res.tempFilePath,
							success: (info) => {
								console.log('压缩图片大小', size, info.size)
								resolve({
									size: info.size,
									path: res.tempFilePath
								})
							},
							fail (err) {
								reject(err)
							}
						})
					},
					fail: (err) => {
						reject(err)
					} 
				})
			}
		}
	})
}

export {
	base64ToPath
}